package cn.edu.hhu.teacher;

import cn.edu.hhu.teacher.bean.Course;
import cn.edu.hhu.teacher.bean.Teacher;
import cn.edu.hhu.teacher.service.CourseService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/teacher/addstudent")
public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CourseService courseService = new CourseService();
        Course course = courseService.get((Teacher) request.getSession().getAttribute("teacher"), request.getParameter("cid"));
        if (course == null) {
            response.sendRedirect(request.getContextPath() + "/teacher/index");
            return;
        }
        String input = request.getParameter("sids");
        if (input == null || input.equals("")) {
            doGet(request, response);
            return;
        }
        String[] sids = input.split("\n");
        StringBuffer msg = new StringBuffer();
        for (String sid : sids) {
            sid = sid.strip();
            if (!sid.equals("")) {
                if (!courseService.addStudent(course, sid)) {
                    msg.append(sid).append("添加失败！<br>");
                }
            }
        }
        msg.append("请返回学生管理页面查看或继续添加学生。");
        request.setAttribute("msg", msg);
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CourseService courseService = new CourseService();
        Course course = courseService.get((Teacher) request.getSession().getAttribute("teacher"), request.getParameter("cid"));
        if (course == null) {
            response.sendRedirect(request.getContextPath() + "/teacher/index");
            return;
        }
        request.setAttribute("course", course);
        request.getRequestDispatcher("/WEB-INF/view/teacher/addstudent.jsp").forward(request, response);
    }
}
